//
//  XYTextView.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/5.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
// 该控件可以动态改变Xib中的属性设置

@IBDesignable class XYTextView: UITextView {
    
    
    // 在外部设置字体大小时同时设置占位文字的文字大小
    override var font: UIFont? {
        
        didSet {
            placeholderLabel.font = font
        }
    }
    // 防止通过xib 设置文字时 不调用是否有文字的判断
    override var text: String? {
        
        didSet {
            placeholderLabel.hidden = hasText()
        }
    }
    // 外部接口 提供在xib中的接口
    @IBInspectable var placeHolder: String? {
        
        didSet {
            
            placeholderLabel.text = placeHolder
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    private func setUpUI() {
        
        addSubview(placeholderLabel)
        // 监听键盘改变通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UITextViewTextDidChangeNotification, object: nil)
    }
    // 通知方法
    @objc private func keyBoardChange(noti:NSNotification) {
        placeholderLabel.hidden = hasText()
    }
    // 移除冬至
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        let size = (placeholderLabel.text! as NSString).boundingRectWithSize(CGSize(width: kSCREENWITH - 2 * placeholderLabel.frame.origin.x, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: placeholderLabel.font], context: nil).size
        placeholderLabel.frame.size = size
    }
    
    // MARK: - 懒加载
    // 占位文字的 label
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.text = "请输入文字"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines = 0
        return label
    }()
}
extension XYTextView {
    
    func insertEmoticon(emoticon: XYEmoticon) {
        
        if emoticon.isEmoji {
            
            self.insertText((emoticon.code! as NSString).emoji())
        }else{
            
            // 取到原有的attributeString
            let originalAttributes = NSMutableAttributedString(attributedString: self.attributedText)
            // 取出图片表情
//            let image = UIImage(named: emoticon.fullPath, inBundle: XYEmoticonTool.sharedEmoticonTool.emoticonBundle, compatibleWithTraitCollection: nil)
            let attachment = XYTextAttachment()
            let attr = attachment.attrubutedStringWith(emoticon, font: self.font!)
//            attachment.emoticon = emoticon
//            attachment.image = image
//            // 调整图片大小
//            let imageWH = self.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -3.5, width: imageWH, height: imageWH)
//            // 设置附件的大小
//            let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            attr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, 1))
            // 获取光标位置
            var range = self.selectedRange
            originalAttributes.replaceCharactersInRange(range, withAttributedString: attr)
            
            self.attributedText = originalAttributes
            
            // 设置光标位置
            range.location += 1; range.length = 0
            self.selectedRange = range
            // 发送系统通知 调用系统代理
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            delegate?.textViewDidChange?(self)
        }
    }
    var getEmoticonText: String {
        
        var string = ""
        // 遍历富文本
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? XYTextAttachment {
                string += attachment.emoticon!.chs!
            }else{
                // 代表是文字
                string += (self.attributedText.string as NSString).substringWithRange(range)
            }
        }
        return string
    }
}
